<template>
  <div>
    <el-form v-model="form">
      <el-form-item>
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item>
        <client-only>
          <VueEditor
            v-model="form.content"
            :editor-toolbar="customToolbar"
            useCustomImageHandler
            @image-added="handleImageAdded"
          />
        </client-only>
      </el-form-item>
      <el-form-item label="选择城市">
        <el-autocomplete
          v-model="form.city"
          :fetch-suggestions="querySearchAsync"
          placeholder="请搜索游玩的城市"
          :trigger-on-focus="false"
        ></el-autocomplete>
      </el-form-item>
    </el-form>
    <div class="submitBtn">
      <el-button type="primary" size="small" @click="submitPost">发布</el-button>
      <span>
        或者
        <a href="javascript:;" @click="saveDraft">保存到草稿</a>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  props: ["data"],
  data() {
    return {
      form: {
        title: "",
        city: "",
        content: "",
      },
      customToolbar: [
        ["bold", "italic", "underline", "strike"],
        ["image"],
        [{ header: "1" }, { header: "2" }],
      ],
    };
  },
  watch: {
    data() {
      this.readDraft();
    },
  },
  methods: {
    //发布
    submitPost() {
      switch (true) {
        case this.form.title.trim() == "":
        case this.form.content.trim() == "":
        case this.form.city.trim() == "":
          this.$alert("请完善内容", "提示", {
            type: "warning",
          });
          return;
      }
      this.$axios({
        url: "/posts",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        },
        method: "post",
        data: this.form,
      })
        .then((res) => {
          if (res.data.message == "新增成功") {
            //提交成功弹出信息
            this.$message.success(res.data.message);
            //清除表单信息
            this.form = {
              title: "",
              city: "",
              content: "",
            };
            //如果发布的是草稿，就把当前草稿删除
            this.$store.commit("draft/delDraft", this.data);
          }
        })
        .catch((err) => {
          if (err.response.status == "401") {
            this.$message.error("请登录！");
          } else if (err.response.status == "500") {
            this.$message.error("服务器出错，请重试！");
          }
        });
    },
    //富文本上传图片
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData();
      formData.append("files", file);
      this.$axios({
        url: "/upload",
        method: "post",
        data: formData,
      }).then((res) => {
        let url = this.$axios.defaults.baseURL + res.data[0].url;
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      });
    },
    // 发布城市
    getCity(val) {
      return this.$axios({
        url: "/airs/city",
        params: {
          name: val,
        },
      }).then((res) => {
        var result = res.data.data.map((item) => {
          return {
            value: item.name,
          };
        });
        return result;
      });
    },
    //城市搜索
    querySearchAsync(val, callback) {
      this.getCity(val).then((res) => {
        callback(res);
      });
    },
    //存草稿
    saveDraft() {
      if (this.form.title.trim() == "") {
        this.$message.error("标题不能为空");
        return;
      }
      var currentTime = new Date();
      var obj = {
        ...this.form,
        time: currentTime.toLocaleString().split(" ")[0],
      };
      this.$store.commit("draft/setDraft", obj);
    },
    //读取草稿
    readDraft() {
      var { time, ...props } = this.$store.state.draft.post[this.data];
      this.form = props;
    },
  },
};
</script>

<style lang="less" scoped>
.submitBtn {
  font-size: 14px;
  span {
    margin-left: 10px;
    a {
      color: #ffa500;
    }
  }
}
</style>